from celery import Celery






import os, sys
# 将django项目根目录加入环境变量
parent_path = os.path.dirname(r'C:\Users\Administrator\Desktop\biquge\qugepro\qugepro')
print(parent_path)
sys.path.append(parent_path)
# 引入django配置文件
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qugepro.settings")
# 启动django
import django
django.setup()
# 操纵数据库
from demo.models import ZhangjieInfo,TextInfo,FictionInfo
from searchs.Quanben import start_url,zhangjie,content
app = Celery('tasks', broker='redis://localhost:6379/1',backend='redis://localhost:6379/2')



#爬取所有从小说信息
@app.task
def fic_name(search):
    lawtid = FictionInfo.objects.latest('id').id#小说库里面最后一个id
    print(lawtid)
    data = start_url(search)
    for i in data:
        print(i)
        lawtid = lawtid+1
        resut = FictionInfo.objects.create(
                                            id=lawtid,
                                            fiction_title=i[0],
                                           fiction_href=i[1],
                                           jianjie=i[2],
                                           author=i[3],
                                           images=i[4],
                                           create_time=i[5],
                                           navid_id=i[6],

                                            )
        if resut:
            print('小说详细储存成功')

        zhangjie_name(i[1],lawtid)



#储存章节
def zhangjie_name(hrefs,fiction_id):
    zhangjie_id = ZhangjieInfo.objects.latest('id').id
    data = zhangjie(hrefs,fiction_id)
    for i in data:
        zhangjie_id=zhangjie_id+1
        print(i)

        resut = ZhangjieInfo.objects.create(id=zhangjie_id,title=i[0],hrefs=i[1],fiction_id=fiction_id)
        if resut:
            print('小说跟章节储存成功')
        text_name(zhangjie_id, i[1])
#储存内容
def text_name(zhangjie_id,hrefs):

    data =content(zhangjie_id,hrefs)
    for i in data:
        print(i)
        rest = TextInfo.objects.create(titles=i[1],font=i[2],zhangje_id=zhangjie_id)
        if rest:
            print('小说内容储存成功')
@app.task(name='start')
def start(search):

    fic_name(search)
